﻿namespace EyeOpen.Dependency
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Reflection;
    using System.Web;

    public static partial class DependencyContainer
    {
        private const string DependencyContainerKey = "DependencyContainer";

        private static IDependencyContainer container;

        private static IDependencyContainer Container
        {
            get
            {
                if (HttpContext.Current == null)
                {
                    if (container == null)
                    {
                        container = IniatializeContainer();
                    }

                    return container;
                }
                else
                {
                    if (HttpContext.Current.Cache[DependencyContainerKey] == null)
                    {
                        HttpContext.Current.Cache[DependencyContainerKey] = IniatializeContainer();
                    }

                    return (IDependencyContainer) HttpContext.Current.Cache[DependencyContainerKey]; 
                }
            }
        }

        private static IDependencyContainer IniatializeContainer()
        {
            string dependencyContainerName = ConfigurationManager.AppSettings["DependencyServiceType"];

            string[] typeTokens = dependencyContainerName.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            Type dependencyContainerType = Assembly.Load(typeTokens[1].Trim()).GetType(typeTokens[0].Trim());
            
            IDependencyService dependencyContainer = (IDependencyService) Activator.CreateInstance(dependencyContainerType);

            return dependencyContainer.GetContainer();
        }
    }
}
